import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { ElMessage } from "element-plus";
import router from "@/router";
import store from "@/store";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = [
  "/login",
  "/home",
  "/learning",
  "/simulator/UpperDu",
  "/simulator/fltctl",
  "/simulator/fuel",
  "/simulator/elec",
  "/simulator/hyd",
  "/learning/index",
  "/test/index",
  "/training/index",
]; // no redirect whitelist

// 检查用户是否有权限访问该路由
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    // 如果路由没有设置 roles，则默认所有人都可以访问
    return true;
  }
}

router.beforeEach(async (to, from, next) => {
  
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        // 检查用户是否有权限访问该路由
        if (hasPermission(store.getters.roles, to)) {
          next();
        } else {
          ElMessage({
            message: "您没有权限访问该页面",
            type: "error",
            duration: 5 * 1000,
          });
          // 不跳转到404，而是停留在当前页面
          console.log("error");

          next(false);
          NProgress.done();
        }
      } else {
        try {
          // 获取用户信息
          const { roles } = await store.dispatch("user/getInfo");
          // 检查用户是否有权限访问该路由
          if (hasPermission(roles, to)) {
            next({ ...to, replace: true });
          } else {
            ElMessage({
              message: "您没有权限访问该页面",
              type: "error",
              duration: 5 * 1000,
            });
            // 不跳转到404，而是跳转到首页或其他有权限的页面
            next("/home");
            NProgress.done();
          }
        } catch (error) {
          await store.dispatch("user/resetToken");
          ElMessage.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      ElMessage({
        message: "请返回登陆！",
        type: "error",
        duration: 5 * 1000,
      });
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
